import { Component, OnInit, OnDestroy, ViewChild, TemplateRef } from '@angular/core'
import { DetailBaseClass } from '@shared/classes/DetailBaseClass'
import { RiskControlScheme } from '@shared/interfaces/risk-control'
import { ActivatedRoute, Router } from '@angular/router'
import { PageService } from '@shared/services/page.service'
import { NzMessageService } from 'ng-zorro-antd'
import { IDetailHeaderTab, RiskTypeMap, StatusTextMap } from '@shared/interfaces/common'
import { RiskService } from '../risk.service'
import { AcquirerService } from '../../acquirer/acquirer.service'
import { DataService } from '@shared/services/data.service'
import { ISearchOption } from '@shared/interfaces/search'
import { deepCopy } from '@delon/util'
import * as dayjs from 'dayjs'
import { RiskStoreService } from '../new/risk-store.service'
import { Validators } from 'app/utils/validator'
import { riskControlSchemeNameLength, riskControlSchemeRemarkLength } from 'app/utils/contraints'
import { I18NService } from '@core'

@Component({
  selector: 'app-risk-detail',
  templateUrl: './detail.component.html',
})
export class RiskDetailComponent extends DetailBaseClass<RiskControlScheme> implements OnInit, OnDestroy {
  @ViewChild('tplCategory') tplCategory: TemplateRef<void>
  @ViewChild('tplControl') tplControl: TemplateRef<void>
  tabs: IDetailHeaderTab[] = [
    { text: this.trans('RISK_CTRL.RULES'), url: './rules' },
    { text: this.trans('GENERAL.INFO.BIZ_LEVEL'), url: './levels' },
  ]

  riskCategoryOptions: ISearchOption[] = [
    { label: this.trans('RISK_CTRL_CATEGORY.NORMAL'), value: 'normal' },
    { label: this.trans('RISK_CTRL_CATEGORY.SPECIAL'), value: 'special' },
  ]

  constructor(
    public route: ActivatedRoute,
    public router: Router,
    public msg: NzMessageService,
    public pageService: PageService,
    private riskService: RiskService,
    public acquirerService: AcquirerService,
    private dataService: DataService,
    private riskStoreService: RiskStoreService,
    private i18n: I18NService,
  ) {
    super(pageService)
  }

  ngOnInit() {
    this.loading = true
    this.id = this.route.snapshot.params['id']
    this.request()
  }

  ngOnDestroy() {
    this.pageService.triggerBaseEdit(false)
  }

  request(): void {
    this.riskService.getOne(this.id).subscribe((riskControlScheme: RiskControlScheme) => {
      this.display(riskControlScheme)
      this.loading = false
    })
  }

  display(riskControlScheme: RiskControlScheme): void {
    this.renderRisk(riskControlScheme)
    this.saveDataToDataStore(deepCopy(riskControlScheme))
    this.initialColumns()
    this.initColumns()
  }

  renderRisk(riskScheme: RiskControlScheme): void {
    this.detailData = riskScheme
  }

  saveDataToDataStore(riskScheme: RiskControlScheme): void {
    this.dataService.setRiskControlScheme(riskScheme)
  }

  cancelBase(): void {
    this.pageService.triggerBaseEdit(false)
    this.resetDetailData()
    this.initColumns()
  }

  resetDetailData(): void {
    this.detailData = this.dataService.riskControlScheme
  }

  saveBase(): void {
    if (!this.checkEditValidation()) {
      this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
      return
    }
    try {
      this.pageService.triggerBaseEdit(false)
      this.updateColumns()
      const { schemeCode } = this.detailData
      this.loading = true
      this.detailData.createdAt = dayjs(this.detailData.createdAt).format()
      this.detailData.updatedAt = dayjs(this.detailData.updatedAt).format()
      this.riskService.update(schemeCode, this.detailData).subscribe(riskControlScheme => {
        this.display(riskControlScheme)
        this.loading = false
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UPDATE_SUCCESS'))
      })
    } catch (err) {
      this.msg.error(this.trans('GENERAL.NOTIFICATION.UPDATE_FAIL'), err.message)
    }
  }

  initialColumns(): void {
    this.firstColumns = [
      {
        span: 6,
        index: 'schemeCode',
        label: 'RISK_CTRL.SCHEME_CODE',
        labelI18n: 'RISK_CTRL.SCHEME_CODE',
        disEditable: true,
      },
      {
        span: 6,
        index: 'schemeName',
        label: 'RISK_CTRL.SCHEME_NAME',
        labelI18n: 'RISK_CTRL.SCHEME_NAME',
        validator: {
          funcs: [Validators.required, Validators.maxLength(riskControlSchemeNameLength)],
          errorTips: [
            this.trans('VALIDATION.REQUIRED', { name: this.trans('RISK_CTRL.SCHEME_NAME') }),
            this.trans('VALIDATION.MAX_LENGTH', { length: riskControlSchemeNameLength }),
          ],
        },
      },
      {
        span: 6,
        index: 'category',
        label: 'RISK_CTRL.CATEGORY',
        labelI18n: 'RISK_CTRL.CATEGORY',
        displayValue: this.trans(RiskTypeMap[this.detailData.category]),
        template: this.tplCategory,
      },
      {
        span: 6,
        index: 'status',
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        displayValue: this.trans(StatusTextMap[this.detailData.status]),
        disEditable: true,
      },
    ]

    this.secondColumns = [
      {
        span: 10,
        index: 'createdAt',
        label: 'GENERAL.INFO.CREATED_AT',
        labelI18n: 'GENERAL.INFO.CREATED_AT',
        type: 'date',
        disEditable: true,
      },
      {
        span: 10,
        index: 'updatedAt',
        label: 'GENERAL.INFO.UPDATED_AT',
        labelI18n: 'GENERAL.INFO.UPDATED_AT',
        type: 'date',
        disEditable: true,
      },
      {
        span: 4,
        index: 'insCode',
        label: 'ROLE.OWNER_INSTITUTION',
        labelI18n: 'ROLE.OWNER_INSTITUTION',
        disEditable: true,
      },
    ]
    this.bottomColumnsRows = [
      [
        {
          span: 16,
          index: 'remark',
          label: 'RISK_CTRL.SCHEME_DESC',
          labelI18n: 'RISK_CTRL.SCHEME_DESC',
          validator: {
            funcs: [Validators.required, Validators.maxLength(riskControlSchemeRemarkLength)],
            errorTips: [
              this.trans('VALIDATION.REQUIRED', { name: this.trans('RISK_CTRL.SCHEME_DESC') }),
              this.trans('VALIDATION.MAX_LENGTH', { length: riskControlSchemeRemarkLength }),
            ],
          },
        },
        {
          span: 8,
          label: 'GENERAL.INFO.OPERATION',
          labelI18n: 'GENERAL.INFO.OPERATION',
          template: this.tplControl,
          operate: true,
        },
      ],
    ]
  }

  // 点击冻结
  freezeDialog() {
    // 冻结TODO
  }

  // 点击解冻
  unfreezeDialog() {
    // 解冻TODO
  }

  // 点击复制
  duplicate() {
    this.acquirerService.getOne(this.detailData.insCode as string).subscribe(data => {
      this.detailData.insCode = {
        code: data.institution.common.insCode,
        num: data.institution.common.insCode,
        level: 'institution',
        nameEN: data.institution.common.insNameEN,
        name: data.institution.common.insName,
      }
      this.riskStoreService.setValue(this.detailData)
      this.router.navigateByUrl('/risk/new')
    })
  }

  trans(str: string, params?: Object): string {
    return this.i18n.fanyi(str, params)
  }
}
